/*
 * Copyright (c) 2021 wuqingtao
 * administrative_division is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *   http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
 * WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 *
 * Author: wuqingtao (wqt_1101@qq.com)
 * CreateTime: 2021-01-25 23:59:35+0800
 */

package main

import (
	"administrativedivision/generator"
	"encoding/json"
	"encoding/xml"
	"flag"
	"fmt"
	"os"

	"howett.net/plist"
)

var (
	file    = flag.String("source", "", "html文本文件")
	url     = flag.String("url", "", "url链接")
	format  = flag.String("format", "json", "输出格式")
	padding = flag.Bool("padding", false, "添加暂不设置")
)

func main() {
	flag.Parse()
	if *file == "" && *url == "" {
		fmt.Fprintln(os.Stderr, "请提供html文本文件或者url链接")
		os.Exit(1)
	}
	var (
		items []*generator.Item
		err   error
	)

	if *url != "" {
		items, err = generator.GetFromURL(*url)
	} else if *file != "" {
		items, err = generator.ReadFromFile(*file)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "读取行政区划数据%s\n", err)
		os.Exit(1)
	}
	if *padding {
		items = append(items, &generator.Item{Code: "830000", Name: "暂不设置"})
	}
	items = generator.ConverToTree(items)
	var b []byte

	switch *format {
	case "", "json":
		b, err = json.MarshalIndent(items, "", " ")
	case "plist":
		b, err = plist.MarshalIndent(items, plist.XMLFormat, " ")
	case "xml":
		b, err = xml.MarshalIndent(generator.ConverToXMLStruct(items), "", " ")
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "conver to %s error %s", *format, err)
		os.Exit(1)
	}
	if *format == "xml" {
		fmt.Print(xml.Header)
	}
	fmt.Printf("%s\n", b)
}
